package aor2.cpu.blockcontrol.horizontal;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;

/**
 * Klasa za parsiranje za MInst sa jednim tipom
 * 
 * @author Erna
 * 
 */

// ERNA: moglo je ovo pametnije samo sa jednom klasom da se uradi, ali poshto je
// drugi
// naziv fajla, napravila sam drugu klasu. tako mi bilo najlakshe.
public class MicroInst1LoaderParser {
	MyContentHandler2 mch = new MyContentHandler2();

	public MicroInst1LoaderParser() {

		InputStream instream = null;
		InputSource is = null;
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			XMLReader xmlReader = spf.newSAXParser().getXMLReader();

			xmlReader.setContentHandler(mch);

			instream = new FileInputStream(
					"src/aor2/common/resources/instSaPr.xml");
			is = new InputSource(instream);

			xmlReader.parse(is);

		} catch (IOException e) {
			e.printStackTrace();
			System.exit(0);
		} catch (SAXException e) {
			e.printStackTrace();
			System.exit(0);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			System.exit(0);
		}

	}

	public ArrayList<MicroInstructionHorizontal> getInstructions() {
		return mch.getInstructions();
	}
}

class MyContentHandler2 extends XMLFilterImpl {
	String signals;
	long code;

	boolean sigb = false;
	boolean codb = false;

	MicroInstructionHorizontal mih;
	long memaddr = 0;

	ArrayList<MicroInstructionHorizontal> instructions = new ArrayList<MicroInstructionHorizontal>();

	public ArrayList<MicroInstructionHorizontal> getInstructions() {
		return instructions;
	}

	public void characters(char[] ch, int start, int length) {
		String gotString = new String(ch, start, length);
		if (sigb) {
			if (!gotString.trim().equals("")) {
				signals = gotString.trim();
				sigb = false;
			}
		}
		if (codb) {
			if (!gotString.trim().equals("")) {
				code = Long.parseLong(gotString.trim());
				sigb = false;
			}
		}
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes attributes) {

		if (localName.equals("signals")) {
			sigb = true;
		} else if (localName.equals("code")) {
			codb = true;
		} else {
			sigb = false;
			codb = false;
		}
	}

	public void endElement(String namespaceURI, String localName, String qName) {
		if (localName.equals("microInst")) {
			mih = new MicroInstructionHorizontal(code);
			String delim = ",";
			String[] tokens = signals.split(delim);

			for (int i = 0; i < tokens.length; i++) {
				mih.addSignal(tokens[i]);
			}
			instructions.add(mih);
		}
	}

}
